package com.zetxek.meteogalicia;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import com.zetxek.meteogalicia.R;

import org.xmlpull.v1.XmlSerializer;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.zetxek.meteogalicia.*;
import com.zetxek.meteogalicia.datasets.Localidad;
import com.zetxek.meteogalicia.datasets.Prediccion;
import com.zetxek.meteogalicia.parsers.*;

public class MeteoGalicia extends ListActivity {

	private final String MY_DEBUG_TAG = "WeatherForcaster";
	private List<Localidad> localidades;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		loadFeed(ParserType.ANDROID_SAX);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		ParserType type = ParserType.values()[item.getItemId()];
		ArrayAdapter<String> adapter = (ArrayAdapter<String>) this
				.getListAdapter();
		if (adapter.getCount() > 0) {
			adapter.clear();
		}
		this.loadFeed(type);
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(localidades
				.get(position).getLink().toExternalForm()));
		this.startActivity(viewMessage);
	}
	
	private void loadLocalidades(){
		try {
			List<String> titles = new ArrayList<String>(localidades.size());
			
			for (Localidad msg : localidades) {
				titles.add(msg.getTitle());
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					R.layout.row, titles);
			this.setListAdapter(adapter);
		} catch (Throwable t) {
			Log.e("MeteoGalicia", t.getMessage(), t);
		}		
	}

	private void loadFeed(ParserType type) {
		try {
			Log.i("MeteoGalicia", "ParserType=" + type.name());
			FeedParser parser = FeedParserFactory.getParser(type);
			long start = System.currentTimeMillis();
			localidades = parser.parse();
			long duration = System.currentTimeMillis() - start;
			Log.i("MeteoGalicia", "Parser duration=" + duration);
			String xml = "xml";//writeXml();
			Log.i("MeteoGalicia", xml);
			List<String> titles = new ArrayList<String>(localidades.size());
			for (Localidad loc : localidades) {
				titles.add(loc.getTitle());
				for (Prediccion pred : loc.getPredicciones() ){
					titles.add(pred.getNomeZona());
				}
				
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					R.layout.row, titles);
			this.setListAdapter(adapter);
		} catch (Throwable t) {
			Log.e("MeteoGalicia", t.getMessage(), t);
		}
	}

	private String writeXml() {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "messages");
			serializer.attribute("", "number", String.valueOf(localidades
					.size()));
			for (Localidad msg : localidades) {
				serializer.startTag("", "message");
				serializer.startTag("", "title");
				serializer.text(msg.getTitle());
				serializer.endTag("", "title");
				serializer.startTag("", "url");
				serializer.text(msg.getLink().toExternalForm());
				serializer.endTag("", "url");
				serializer.startTag("", "body");
				serializer.text(msg.getDescription());
				serializer.endTag("", "body");
				serializer.endTag("", "message");
			}
			serializer.endTag("", "messages");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}